package swiftdecode

import (
	"fmt"
	"log"
	"time"

	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket/pcap"
)

var (
	snapshot_len int32 = 1024
	promiscuous  bool  = false
	err          error
	timeout      time.Duration = 30 * time.Second
	handle       *pcap.Handle
	//将对每个包重复使用这些
	ethLayer layers.Ethernet
	ipLayer  layers.IPv4
	tcpLayer layers.TCP
	tlsLayer layers.TLS
)

/*
更快的解包
*/
func Interpret(device string) {
	handle, err := pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Close()
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	for packet := range packetSource.Packets() {
		parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &ethLayer, &ipLayer, &tcpLayer, &tlsLayer)
		foundLayerTypes := []gopacket.LayerType{}
		err = parser.DecodeLayers(packet.Data(), &foundLayerTypes)
		if err != nil {
			fmt.Println("parser layers error :", err)
		}
		for _, layerType := range foundLayerTypes {
			if layerType == layers.LayerTypeIPv4 {
				fmt.Printf("IPv4:%s->%s\n", ipLayer.SrcIP, ipLayer.DstIP)
			}
			if layerType == layers.LayerTypeTCP {
				fmt.Printf("TCP port:%d->%d,SYN=%v,ACK=%v \n", tcpLayer.SrcPort, tcpLayer.DstPort, tcpLayer.SYN, tcpLayer.ACK)
			}
			if layerType == layers.LayerTypeTLS {
				fmt.Println(tlsLayer)
			}
		}
	}
}
